export enum BaseMessageType {
  GetLandlordPid = 'get-landlord-pid',
  GotLandlordPid = 'got-landlord-pid',
}

export interface Message {
  type: string,
  to?: number,
  msg?: any,
}

export class Communication {
  private messages: Map<string, Function[]> = new Map();

  constructor() {
    this.init();
  }

  public getLandlordPid() {
    return new Promise(resolve => {
      process.send?.({ type: BaseMessageType.GetLandlordPid });
      process.on('message', (data: Message) => {
        if (data.type === BaseMessageType.GotLandlordPid) {
          resolve(data.msg);
        }
      });
    });
  }

  public register(type: string, target: Function) {
    if (this.messages.has(type)) {
      this.messages.get(type)?.push(target);
    } else {
      this.messages.set(type, [target]);
    }
  }

  private init() {
    process.on('message', (message: Message) => {
      if (this.messages.has(message.type)) {
        const targets = this.messages.get(message.type);
        console.error(targets);
        targets?.map(target => (target(message)));
      }
    });
  }
}

const communication = new Communication();
export default communication;
